package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.entity.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocal;
import com.heima.user.dto.AuthorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApAuthor;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleClient;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-20
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult login(LoginDto loginDto) {
//        数据校验
        if (loginDto == null || StringUtils.isEmpty(loginDto.getEquipmentId()) && StringUtils.isEmpty(loginDto.getPhone()) && StringUtils.isEmpty(loginDto.getPassword())){
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        判断密码账号是否为空
        if (!StringUtils.isEmpty(loginDto.getPhone()) && !StringUtils.isEmpty(loginDto.getPassword())){
            Map<String,Object> map = new HashMap<>();
//            查询数据判断密码是否正确
            LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();
            query.eq(ApUser::getPhone,loginDto.getPhone());
            ApUser one = this.getOne(query);
            if (one == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
//            获取盐
            String salt = one.getSalt();
//            密码加密
            String  password = loginDto.getPassword() + salt;
            String password1 = DigestUtils.md5DigestAsHex(password.getBytes());
//            判断密码是否正确
            if (one.getPassword().equals(password1)){
               Map<String,Object> token = new HashMap<>();
               token.put("userId",one.getId());
                String token1 = AppJwtUtil.getToken(token);
                map.put("phone",one.getPhone());
                map.put("token",token1);
                return ResponseResult.okResult(map);
            }
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
//             判断设备号是否为空
        if (!StringUtils.isEmpty(loginDto.getEquipmentId())){
            Map<String,Object> map = new HashMap<>();
//                存入设备号
            Map<String,Object> token = new HashMap<>();
            token.put("userId",0);
            String token1 = AppJwtUtil.getToken(token);
            map.put("phone",0);
            map.put("token",token1);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }


    @Autowired
    private ArticleClient articleClient;
    @Autowired
    private IApUserFollowService apUserFollowService;
    /**
     * 关注作者和取消作者
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        User user = AppThreadLocal.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
//        创建关注列表
        ApUserFollow apUserFollow = new ApUserFollow();
        apUserFollow.setUserId(user.getUserId());
//        查询用户表
        ApUser apUser = this.getById(user.getUserId());
        apUserFollow.setUserName(apUser.getName());

//        远程查询出作者信息
        ResponseResult<ApAuthor> authorResponseResult = articleClient.getById(dto.getAuthorId());
        if (authorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApAuthor apAuthor = authorResponseResult.getData();
            if (apAuthor != null){
                apUserFollow.setFollowId(apAuthor.getId());
                apUserFollow.setFollowName(apAuthor.getName());
            }
        }
        apUserFollow.setLevel(1);
        apUserFollow.setCreatedTime(new Date());
//        查询关注列表是否存在信息
        LambdaUpdateWrapper<ApUserFollow> query = new LambdaUpdateWrapper<>();
        query.eq(ApUserFollow::getFollowId,apUserFollow.getFollowId());
        query.eq(ApUserFollow::getUserId,user.getUserId());
        ApUserFollow one = apUserFollowService.getOne(query);
//        判断是否存在
        if (one == null){
//            查询不到，没有添加
            if (dto.getOperation() == 0) {
                apUserFollowService.save(apUserFollow);
            }
        }else {
            if (dto.getOperation() == 1){
                apUserFollowService.removeById(apUserFollow);
            }
        }

        return ResponseResult.okResult();
    }
}
